package com.bysc.joinservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bysc.baseservice.handler.BaiYunException;
import com.bysc.commonutils.ResultCode;
import com.bysc.commonutils.Results;
import com.bysc.commonutils.constant.MessageConstant;
import com.bysc.commonutils.utils.JwtUtils;
import com.bysc.commonutils.vo.JoinUserDept;
import com.bysc.joinservice.entity.JoinDept;
import com.bysc.joinservice.entity.vo.JoinUserDeptQueryVo;
import com.bysc.joinservice.service.JoinDeptService;
import com.bysc.joinservice.service.JoinUserDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/joinservice/join-user-dept")
@Api(tags = "用户与部门关系管理")
public class JoinUserDeptController {

    @Autowired
    private JoinUserDeptService joinUserDeptService;
    @Autowired
    private JoinDeptService  joinDeptService;

    @ApiOperation(value = "绑定或更新用户与部门")
    @PostMapping("bindOrUpdateUserDept")
    public Results bindOrUpdateUserDept(@ApiParam(name = "UserDeptInfo", value = "用户与部门绑定信息", required = true) @RequestBody JoinUserDept userDept, HttpServletRequest request) {
        try {
            String TOKEN_clubId = JwtUtils.getClubIdByJwtToken(request);
            LambdaQueryWrapper<JoinUserDept> wrapper = new LambdaQueryWrapper<>();
            if (!StringUtils.isEmpty(TOKEN_clubId)) {
                wrapper.eq(JoinUserDept::getClubId, TOKEN_clubId);
            }
            if(!StringUtils.isEmpty(userDept.getUserId())){
                wrapper.eq(JoinUserDept::getUserId, userDept.getUserId());
            }
            JoinUserDept existingUserDept = joinUserDeptService.getOne(wrapper);
            if (existingUserDept != null) {
                // 如果存在，则更新
                userDept.setUserId(userDept.getId());
                userDept.setClubId(TOKEN_clubId);
                joinUserDeptService.updateById(userDept);
            } else {
                // 如果不存在，则添加
                joinUserDeptService.save(userDept);
            }
            return Results.ok().message(MessageConstant.EDIT_DEPTUSER_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.EDIT_DEPTUSER_FAIL);
        }
    }

    @ApiOperation(value = "根据用户id查找绑定的部门")
    @GetMapping("getDeptsByUserId/{userId}")
    public Results getDeptsByUserId(@ApiParam(name = "userId", value = "用户id", required = true) @PathVariable String userId) {
        try {
            JoinUserDept userDept = joinUserDeptService.getOne(new QueryWrapper<JoinUserDept>().eq("user_id", userId));
            return Results.ok().data("userDept", userDept).message(MessageConstant.QUERY_DEPTUSER_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_DEPTUSER_FAIL);
        }
    }

    /*
    * 新增根据cluId分页查询
    * */
    @ApiOperation(value = "分页查找对应社团的用户与部门的绑定关系")
    @PostMapping("getUserDeptsByclubId/{page}/{limit}")
    public Results getUserDeptsByclubId(
            @ApiParam(name = "page", value = "当前页码", required = true) @PathVariable Integer page,
            @ApiParam(name = "limit", value = "每页显示的记录数", required = true) @PathVariable Integer limit,
            @ApiParam(name = "joinUserDept", value = "查询条件", required = false) @RequestBody JoinUserDeptQueryVo queryVo, HttpServletRequest request) {
        try {
            Page<JoinUserDept> pageResult = new Page<>(page, limit);
            LambdaQueryWrapper<JoinUserDept> wrapper = new LambdaQueryWrapper<>();
            String TOKEN_clubId= JwtUtils.getClubIdByJwtToken(request);
            if(!StringUtils.isEmpty(queryVo.getClubId())){
                wrapper.eq(JoinUserDept::getClubId, queryVo.getClubId());
            }
            else{
                if(!StringUtils.isEmpty(TOKEN_clubId)){
                    wrapper.eq(JoinUserDept::getClubId, TOKEN_clubId);
                }
            }
            if (!StringUtils.isEmpty(queryVo.getUserId())) {
                wrapper.eq(JoinUserDept::getUserId, queryVo.getUserId());
            }
            if (!StringUtils.isEmpty(queryVo.getDeptId())) {
                wrapper.eq(JoinUserDept::getDeptId, queryVo.getDeptId());
            }
            if (!StringUtils.isEmpty(queryVo.getRoleId())) {
                wrapper.eq(JoinUserDept::getRoleId, queryVo.getRoleId());
            }

            if (!StringUtils.isEmpty(queryVo.getStart())) {
                wrapper.ge(JoinUserDept::getGmtCreate, queryVo.getStart());
            }
            if (!StringUtils.isEmpty(queryVo.getEnd())) {
                wrapper.le(JoinUserDept::getGmtCreate, queryVo.getEnd());
            }
            if (!StringUtils.isEmpty(queryVo.getUserName())) {
                wrapper.like(JoinUserDept::getUserName, queryVo.getUserName());
            }
            IPage<JoinUserDept> iPage = joinUserDeptService.page(pageResult, wrapper);
            for (JoinUserDept joinUserDept : iPage.getRecords()){
                if (joinUserDept != null) {
                    joinUserDept.setDeptName(joinDeptService.getById(joinUserDept.getDeptId()).getName());
                }
            }
            return Results.ok().data("list", iPage).message(MessageConstant.QUERY_DEPTUSER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_DEPTUSER_FAIL);
        }
    }

    @ApiOperation(value = "根据关系id删除用户与部门的绑定关系")
    @DeleteMapping("deleteUserDeptById/{id}")
    public Results deleteUserDeptById(@ApiParam(name = "id", value = "绑定关系id", required = true) @PathVariable String id) {
        try {
            JoinUserDept userDept = joinUserDeptService.getById(id);
            if (userDept != null) {
                joinUserDeptService.removeById(id);
            }
            return Results.ok().message(MessageConstant.DELETE_DEPTUSER_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.DELETE_DEPTUSER_FAIL);
        }
    }

    @ApiOperation(value = "解绑用户与部门")
    @DeleteMapping("unbindUserDept/{userId}/{deptId}")
    public Results unbindUserDept(@ApiParam(name = "userId", value = "用户id", required = true) @PathVariable String userId,
                                  @ApiParam(name = "deptId", value = "部门id", required = true) @PathVariable String deptId) {
        try {
            JoinUserDept userDept = joinUserDeptService.getOne(new QueryWrapper<JoinUserDept>()
                    .eq("user_id", userId)
                    .eq("dept_id", deptId));
            if (userDept != null) {
                joinUserDeptService.removeById(userDept.getId());
            }
            return Results.ok().message(MessageConstant.EDIT_DEPTUSER_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.EDIT_DEPTUSER_FAIL);
        }
    }

    @ApiOperation(value = "查询所有成员id")
    @GetMapping("getAllJoin")
    public Results getAllJoin() {
        try {
            QueryWrapper<JoinUserDept> wrapper = new QueryWrapper<>();
            wrapper.select("user_id");
            List<JoinUserDept> list = joinUserDeptService.list(wrapper);
            ArrayList<String> res = new ArrayList<>();
            for (JoinUserDept joinUserDept : list) {
                res.add(joinUserDept.getUserId());
            }
            return Results.ok().data("ids", res).message(MessageConstant.QUERY_DEPTUSER_SUCCESS);
        } catch (Exception e) {
            throw new BaiYunException(ResultCode.ERROR, MessageConstant.QUERY_DEPTUSER_FAIL);
        }
    }
}
